package cn.stylefeng.guns.gateway.modular.validate;

import cn.hutool.core.util.StrUtil;
import cn.stylefeng.roses.kernel.auth.api.exception.AuthException;
import cn.stylefeng.roses.kernel.auth.api.exception.enums.AuthExceptionEnum;
import cn.stylefeng.roses.kernel.scanner.api.pojo.resource.ResourceDefinition;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 校验Api接口权限，同时校验Api的token和权限
 *
 * @author fengshuonan
 * @since 2023/8/7 22:21
 */
@Service
@Slf4j
public class ApiAuthService {

    @Resource
    private TokenValidateService tokenValidateService;

    @Resource
    private PermissionValidateService permissionValidateService;

    /**
     * 进行API的token校验，包含认证和鉴权
     *
     * @author fengshuonan
     * @since 2023/8/7 22:38
     */
    public void validate(String token, ResourceDefinition resourceDefinition) {

        // 校验token
        if (resourceDefinition.getRequiredLoginFlag()) {

            // token为空，返回用户校验失败
            if (StrUtil.isEmpty(token)) {
                throw new AuthException(AuthExceptionEnum.TOKEN_GET_ERROR);
            }

            // 校验token和用户会话信息是否正确
            tokenValidateService.validateToken(token);
        }

        // 执行权限校验
        if (resourceDefinition.getRequiredPermissionFlag()) {

            // token为空，返回用户校验失败
            if (StrUtil.isEmpty(token)) {
                throw new AuthException(AuthExceptionEnum.TOKEN_GET_ERROR);
            }

            // 进行当前接口的权限校验
            permissionValidateService.validatePermission(token, resourceDefinition);
        }
    }

}
